from database.user import UserTable
from models.account import Account
from models.user import User
import time
import json
from utils.aes import aesEncrypt, aesDecrypt

global_duration = 60 * 60 * 24 * 7

aesKey = 'dofigjrmb9s84s2z'

class Token():

    def CreateToken(login : Account):
        id = 0
        with UserTable() as tb:
            id = tb.login(login)
        if not id:
            return None
        loginTimeStamp = int(time.time())
        duration = global_duration
        return Token(id, loginTimeStamp, duration)

    def Parse(token : str):
        try:
            data = json.loads(aesDecrypt(aesKey, token))
            return Token(data['userId'], data['loginTime'], data['duration'])
        except:
            return None

    def __init__(self, userId : int, loginTimeStamp : int, duration : int) -> None:
        self.userId : int = userId
        self.loginTime : int = loginTimeStamp
        self.duration : int = duration

    def getUser(self) -> User:
        with UserTable() as tb:
            return tb.getUser(self.userId)

    def isExpired(self) -> bool:
        return int(time.time()) > self.loginTime + self.duration

    def __str__(self) -> str:
        data = json.dumps(self.__dict__)
        return aesEncrypt(aesKey, data)
        
